/**
 * 传送门组件
 */
import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';

// create your forceUpdate hook
function useForceUpdate() {
  const [, set] = useState(true); // boolean state
  return () => {
    set((v) => !v); // toggle the state to force render
  };
}

const Portal = ({ targetDom, children }) => {
  const forceUpdate = useForceUpdate();
  useEffect(() => {
    const timer = setTimeout(forceUpdate, 0);
    return () => {
      clearTimeout(timer);
    };
  }, [targetDom]);

  if (targetDom) {
    const domNode = document.querySelector(targetDom);
    if (domNode) {
      return createPortal(children, domNode);
    }
  }
  return children;
};

export default Portal;
